package com.study.happystudy.controller;

import cn.hutool.core.date.DateUtil;
import com.study.happystudy.entity.ResultEntity;
import com.study.happystudy.po.Emotion;
import com.study.happystudy.po.EmotionData;
import com.study.happystudy.service.impl.EmotionServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("emotion/")
public class EmotionController {
    @Resource
    EmotionServiceImpl emotionService;

    @PostMapping("insert")
    public String insert(@RequestParam("userId") int userId, @RequestParam("emotion") String emotion) {
        Date currentDate = new Date();
        String date = DateUtil.format(currentDate, "yyyy-MM-dd");

        if (emotionService.isExist(userId, date) == 1) {
            try {
                emotionService.updateEmotion(emotion, userId, date);
                return ResultEntity.Success(1, "修改成功");
            } catch (Exception e) {
                return ResultEntity.Fail(-1, "修改失败");
            }
        }

        try {
            emotionService.insert(userId, emotion);
            return ResultEntity.Success(1, "操作成功");
        } catch (Exception e) {
            return ResultEntity.Fail(-1, "操作失败");
        }
    }

    @GetMapping("selectByUserId")
    public Object selectByUserId(@RequestParam("userId") int userId) {
        List<Emotion> emotions = emotionService.selectByUserId(userId);
        Set<String> yearMonth = emotions.stream().map(emotion -> emotion.getDate().substring(0, 7)).collect(Collectors.toSet());
        List<EmotionData> res = new ArrayList<>();
        for(String ym : yearMonth){
            res.add(emotionService.getEmotionDataByMonth(userId, ym));
        }
        return res;
    }

    @PostMapping("updateEmotion")
    public String updateEmotion(String emotion, int userId, String date) {
        try {
            emotionService.updateEmotion(emotion, userId, date);
            return ResultEntity.Success(1, "操作成功");
        } catch (Exception e) {
            return ResultEntity.Fail(-1, "操作失败");
        }
    }

    @GetMapping("getEmotionDataByMonth")
    public Object getEmotionDataByMonth(@RequestParam("userId") int userId, @RequestParam("yearMonth") String yearMonth) {
        try {
            EmotionData emotionData = emotionService.getEmotionDataByMonth(userId, yearMonth);
            return emotionData;
        } catch (Exception e) {
            return ResultEntity.Fail(-1, e.getMessage());
        }
    }
}
